$(document).ready(function() {
	//$('.button').button().css('cursor','pointer');
	
	var iw = $('.preview img').width();
	var ih = $('.preview img').height();
	$('.overlay').css('width', iw).css('height', ih);
	$('.preview').css('width', iw).css('height', ih);
	var length = (iw>ih)? ih*0.9 : iw*0.9;
	var fw = length;
	var fh = length;
	var topH = (ih - fh) / 2;
	var leftW = (iw - fw) / 2;
	var src = $('.preview img').attr('src');
	var hlX = -leftW-1; // -1 is added to accommodate the added border width
	var hlY = -topH-1;
	$('.highlight').css({
		backgroundImage: 'url('+src+')',
		backgroundPosition: hlX+"px "+hlY+"px",
		width: fw,
		height: fh,
		top: topH,
		left: leftW,
		cursor:'move'
	});
	
	$('.highlight').resizable({
		aspectRatio: 1,
		containment: '.preview',
		minHeight: 140,
		resize: function(event, ui) {
				$(this).css({backgroundPosition: hlX+1+"px "+hlY+"px"});
			},
		stop: function(event, ui) {
				var w = $(this).css('width');
				var h = $(this).css('height');
				fw = parseInt(w.substring(0,w.indexOf('px')));
				fh = parseInt(h.substring(0,h.indexOf('px')));
			}
	});	
	
	var startX;
	var startY;
	var deltaX;
	var deltaY;
	
	$('.highlight').bind( 'dragstart', function(event){
		startX = event.pageX;
		startY = event.pageY;
	});
	
	$('.highlight').bind( 'drag', function(event){
		deltaY = event.pageY-startY;
		deltaX = event.pageX-startX;
		/* top delta limit */
		if(topH+deltaY<0) {
			deltaY=-topH;
		}
		/* bottom delta limit */
		if(topH+fw+deltaY>ih) {
			deltaY=ih-topH-fw-1;
		}
		/* right delta limit */
		if(leftW+fh+deltaX>iw) {
			deltaX=iw-leftW-fh-1;
		}
		/* left delta limit */
		if(leftW+deltaX<0) {
			deltaX=-leftW;
		}
		var bgX = hlX-deltaX;
		var bgY = hlY-deltaY;
		/*$('.test').html('Image Width = '+iw+', ih = '+ih+'<br/>'+
				'Frame Width = ' + fw+', Frame Height = '+fh+'<br/>'+
				'left = '+leftW+', top = '+topH+'<br/>'+
				'delta X = ' + deltaX+', delta Y = '+deltaY+'<br/>'
		);*/
		$(this).css({
			top:topH + deltaY, 
			left:leftW + deltaX,
			backgroundPosition: bgX+"px "+bgY+"px"
		});		
	});
	
	$('.highlight').bind( 'dragend', function(event){
		topH += deltaY;
		leftW += deltaX;
		hlX -= deltaX;
		hlY -= deltaY;
	});
	
	/* Save photo */
	$('.profile-photo-save').click(function(event){
		location.href='profile-photo-save.action?x='+leftW+
			'&y='+topH+'&w='+fw+'&h='+fh+
			'&tempFilePaths='+$(this).attr('name');
	});
});